from app.Pojo.BUser import BUser



class UserMapper:
    def __init__(self, db):
        self.db = db

    def create_user(self, user):
        """创建用户"""
        self.db.session.add(user)
        self.db.session.commit()
        return user

    def delete_users(self, ids):
        """批量删除用户"""
        BUser.query.filter(BUser.id.in_(ids)).delete(synchronize_session=False)
        self.db.session.commit()

    def get_by_id(self, id):
        """根据ID获取用户"""
        return BUser.query.get(id)

    def get_by_username(self, username):
        """根据用户名获取用户"""
        return BUser.query.filter_by(username=username).first()

    def update_user(self, user):
        """更新用户信息"""
        self.db.session.commit()
        return user

    def list_users(self, page, page_size):
        """分页查询用户"""
        total = BUser.query.count()
        users = BUser.query.order_by(BUser.create_time.desc()) \
            .limit(page_size) \
            .offset((page - 1) * page_size) \
            .all()
        return users, total

    def delete_user(self, id):
        """删除用户"""
        BUser.query.filter_by(id=id).delete()
        self.db.session.commit()

    def search_users(self, username):
        """根据用户名搜索用户"""
        if not username:
            return []
        return BUser.query.filter(BUser.username.like(f'%{username}%')).all()